import { DownOutlined, UpOutlined } from '@ant-design/icons';
import {
  Button,
  Input,
  Space,
  TableColumnsType,
  DatePicker,
  message,
  Select,
  Spin,
  Flex,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import './index.css';
import PagesHeader from '@/components/pages-header';
import Tables from '@/components/tables/tables';
import limitsService from '@/api/services/limitsService.ts';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { useSize } from 'ahooks';
import NotData from '@/components/NotData';
import { useParams } from '@/router/hooks';
import TipDesc from '@/components/tipDesc/tipDesc';

dayjs.locale('zh-cn');

interface DataType {
  key: string;
  action_time: string;
  user_name: string;
  role: string;
  action_type: string;
  action_detail: string;
  ip: string;
  device: string;
  isExpanded?: boolean; // 添加行展开状态
}

interface page {
  list?: any[];
  page: number;
  page_size: number;
  total?: number;
  user_name?: string;
  action_type?: string;
  start_time?: string | null;
  end_time?: string | null;
}

const dateFormat = 'YYYY-MM-DD';

const BehaviorLog = () => {
  const { RangePicker } = DatePicker;
  const { user_name, action_type, end_time, start_time } = useParams() as {
    user_name: string;
    action_type: string | null;
    start_time: string | null;
    end_time: string | null;
  };

  // 为每一行添加展开状态
  const [expandedRows, setExpandedRows] = useState<Record<string, boolean>>({});

  // 记录每行文本实际内容节点的 ref，用于计算是否溢出两行
  const contentRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const [overflowRowMap, setOverflowRowMap] = useState<Record<string, boolean>>({});

  // 容器尺寸变化时重新检测（响应式场景）
  const containerRef = useRef<HTMLDivElement>(null);
  const containerSize = useSize(containerRef);

  const toggleRowExpansion = (key: string) => {
    setExpandedRows((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: '时间',
      dataIndex: 'action_time',
      width: 200,
      render: (text: string) => <span>{dayjs(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '用户名',
      dataIndex: 'user_name',
      width: 150,
    },
    {
      title: '角色',
      width: 150,
      dataIndex: 'role',
    },
    {
      title: '操作类型',
      width: 160,
      dataIndex: 'action_type',
    },
    {
      title: '操作详情',
      dataIndex: 'action_detail',
      width: 342,
      render: (_, record) => {
        const isExpanded = expandedRows[record.key] || false;

        return (
          <>
            <div
              className={`${
                !isExpanded ? 'line-clamp-2' : ''
              }   w-[320px] overflow-hidden  text-ellipsis  `}
            >
              <div
                ref={(el) => {
                  contentRefs.current[record.key] = el;
                }}
                className="text-sm text-[#292D32]"
              >
                {record.action_detail}
              </div>
            </div>
            {overflowRowMap[record.key] && (
              <div className="cursor-pointer">
                {!isExpanded ? (
                  <div
                    className="flex items-center text-sm text-[#1B6DFA]"
                    onClick={() => toggleRowExpansion(record.key)}
                  >
                    <DownOutlined />
                    展开
                  </div>
                ) : (
                  <div
                    className="flex items-center text-sm text-[#1B6DFA]"
                    onClick={() => toggleRowExpansion(record.key)}
                  >
                    <UpOutlined />
                    收起
                  </div>
                )}
              </div>
            )}
          </>
        );
      },
    },
    {
      width: 180,
      title: 'IP地址',
      dataIndex: 'ip',
    },
    {
      title: '设备信息',
      dataIndex: 'device',
      width: 122,
    },
  ];

  const [isNoData, setIsNoData] = useState<boolean>(false);
  const [getdata, setgetdata] = useState({
    list: [],
    total: 0,
  });

  const [BehaviorPage, setBehaviorPage] = useState<page>({
    page: 1,
    page_size: 10,
    user_name: user_name || '',
    action_type: action_type || '',
    start_time: start_time || null,
    end_time: end_time || null,
  });

  const [startTime, setStartTime] = useState(start_time || null);
  const [endTime, setEndTime] = useState(end_time || null);
  const [userName, setUserName] = useState(user_name || '');
  const [actionType, setActionType] = useState(action_type || null);
  const [actionTypeList, setActionTypeList] = useState([
    { value: 'jack', label: 'Jack' },
    { value: 'lucy', label: 'Lucy' },
    { value: 'Yiminghe', label: 'yiminghe' },
  ]);

  const getBehaviorList = async () => {
    try {
      const res = await limitsService.limitsList(BehaviorPage);
      const dataWithKeys = res.list.map((item: any, index: number) => ({
        ...item,
        key: `${item.action_time}_${item.user_name}_${index}`,
      }));

      setgetdata({
        list: dataWithKeys,
        total: res.total,
      });
      setIsNoData(true);

      // 重置展开状态
      setExpandedRows({});
    } catch (error) {
      message.error(error);
    }
  };

  // 获取可选操作类型
  const getActionType = async () => {
    let arr: any = [];
    try {
      const res = await limitsService.limitsActionType();
      for (let i = 0; i < res.length; i++) {
        arr.push({ value: res[i], label: res[i] });
      }
      setActionTypeList(arr);
    } catch (error) {
      message.error(error);
    }
  };

  useEffect(() => {
    getBehaviorList();
  }, [BehaviorPage.page]);

  useEffect(() => {
    getActionType();
  }, []);

  // 根据实际渲染结果检测每行是否发生溢出（超过两行）
  useEffect(() => {
    const map: Record<string, boolean> = {};
    getdata.list.forEach((item: any) => {
      const el = contentRefs.current[item.key];
      if (el) {
        const style = window.getComputedStyle(el);
        const lineHeightPx = style.lineHeight;
        let lineHeight = 0;
        if (lineHeightPx.endsWith('px')) {
          lineHeight = parseFloat(lineHeightPx);
        } else {
          // 退化处理：无法解析时使用字体大小的 1.2 倍
          const fontSize = parseFloat(style.fontSize || '14');
          lineHeight = fontSize * 1.2;
        }
        const maxTwoLinesHeight = lineHeight * 2 + 1; // 误差补偿
        map[item.key] = el.scrollHeight > maxTwoLinesHeight;
      }
    });
    setOverflowRowMap(map);
  }, [getdata.list, containerSize?.width]);

  const resetGetData = () => {
    BehaviorPage.page = 1;
    BehaviorPage.user_name = '';
    BehaviorPage.action_type = '';
    BehaviorPage.list = [];
    BehaviorPage.start_time = null;
    BehaviorPage.end_time = null;
    setStartTime('');
    setEndTime('');
    setUserName('');
    setActionType(null);
    setBehaviorPage({ ...BehaviorPage });
    getBehaviorList();
  };

  return (
    <div ref={containerRef} className="flex  h-full flex-col">
      {isNoData ? (
        <>
          <PagesHeader>
            行为日志
            <TipDesc title="记录平台内关键操作和事件的详细流水" />
          </PagesHeader>
          <div className=" flex flex-1 flex-col rounded-default bg-[#FFF] px-5">
            <div className=" my-5 flex items-center justify-between  ">
              <div className="flex items-center ">
                <div className="mr-[10px]">用户名</div>
                <Input
                  placeholder="输入用户名"
                  onChange={(e) => {
                    setBehaviorPage((prev) => ({
                      ...prev,
                      page: 1,
                      user_name: e.target.value,
                    }));
                    setUserName(e.target.value);
                  }}
                  value={userName}
                  style={{
                    height: '32px',
                    width: '200px',
                  }}
                />
                <div className="ml-[20px] mr-[10px]">操作类型</div>
                <Select
                  placeholder="选择操作类型"
                  className="nowheel select w-52"
                  onChange={(value) => {
                    setBehaviorPage((prev) => ({
                      ...prev,
                      page: 1,
                      action_type: value,
                    }));
                    setActionType(value);
                  }}
                  options={actionTypeList}
                  value={actionType}
                  showSearch
                  allowClear
                />

                <div className="ml-[20px] mr-[10px]">时间</div>
                <Space direction="vertical" size={12}>
                  <RangePicker
                    style={{ borderRadius: '6px', borderColor: '#E5E6EB' }}
                    onChange={(_, dateStrings) => {
                      setStartTime(dateStrings[0]);
                      setEndTime(dateStrings[1]);

                      setBehaviorPage((prev) => ({
                        ...prev,
                        page: 1,
                        start_time: dateStrings[0]
                          ? dateStrings[0] === dateStrings[1]
                            ? dateStrings[0] + ' 00:00:00'
                            : dateStrings[0]
                          : null,
                        end_time: dateStrings[1]
                          ? dateStrings[0] === dateStrings[1]
                            ? dateStrings[1] + ' 23:59:59'
                            : dateStrings[1]
                          : null,
                      }));
                    }}
                    value={[startTime ? dayjs(startTime) : null, endTime ? dayjs(endTime) : null]}
                    format={dateFormat}
                  />
                </Space>
                <Button
                  className="ml-[15px] mr-[0px] w-[60px] rounded-md !border-@brand-color !text-@brand-color"
                  onClick={getBehaviorList}
                >
                  搜索
                </Button>
                <div
                  className="mx-3 flex h-[32px] w-[60px] cursor-pointer items-center justify-center rounded-md border border-[#E5E6EB] bg-[#F7F8FA]  text-[#1D2129]"
                  onClick={resetGetData}
                >
                  重置
                </div>
              </div>
            </div>

            {getdata.list.length > 0 ? (
              <div className="h-full flex-1 rounded-default  text-[#292D32]">
                <Tables<DataType>
                  columns={columns}
                  dataSource={getdata.list}
                  pagination={false}
                  rowBgClassName="bg-[#FFF]"
                  scroll={{ x: 'calc(100vw - 400px)', y: 'calc(100vh - 306px)' }}
                  paginationProps={{
                    total: getdata.total,
                    current: BehaviorPage.page,
                    pageSize: BehaviorPage.page_size,
                    onChange: (page, pageSize) => {
                      BehaviorPage.page = page;
                      BehaviorPage.page_size = pageSize;
                      getBehaviorList();
                    },
                  }}
                />
              </div>
            ) : (
              <NotData iconSize={80} textClassName={'text-sm'} />
            )}
          </div>
        </>
      ) : (
        <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
          <Spin size="large" />
        </Flex>
      )}
    </div>
  );
};

export default BehaviorLog;
